package com.qd.p2p.web.action.additional;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Result;
import org.springframework.beans.factory.annotation.Qualifier;

import com.google.common.base.Splitter;
import com.opensymphony.xwork2.ModelDriven;
import com.qdlc.p2p.biz.executer.impl.NewActivityAwardExecutor;
import com.qdlc.p2p.biz.service.CollectPayService;
import com.qdlc.p2p.biz.service.UserIdentifyService;
import com.qdlc.p2p.biz.service.UserRedEnvelopeService;
import com.qdlc.p2p.biz.service.UserService;
import com.qdlc.p2p.biz.web.action.BaseAction;
import com.qdlc.p2p.common.constant.NotifyUrl;
import com.qdlc.p2p.common.constant.RedEnvelopeType;
import com.qdlc.p2p.common.constant.RedUseType;
import com.qdlc.p2p.common.core.ReturnResult;
import com.qdlc.p2p.common.enums.EnumActicityPlanNid;
import com.qdlc.p2p.common.exception.RedEnvelopeException;
import com.qdlc.p2p.common.util.MessageUtil;
import com.qdlc.p2p.common.util.StringUtil;
import com.qdlc.p2p.dal.common.SystemConfigHelper;
import com.qdlc.p2p.dal.common.SystemConfigHelper.Nid;
import com.qdlc.p2p.dal.common.model.jpa.PageDataList;
import com.qdlc.p2p.dal.dto.TppTradeLog;
import com.qdlc.p2p.dal.dto.User;
import com.qdlc.p2p.dal.dto.UserIdentify;
import com.qdlc.p2p.dal.model.UserRedEnvelopeModel;
import com.qdlc.p2p.dal.util.UserTypeUtils;
import com.qdlc.p2p.dal.util.UserUtils;

/**
 * 红包
 *
 * @author ylx
 * @version 2.0
 * @date 2015年5月19日 上午11:16:47
 */
public class UserRedEnvelopeAction extends BaseAction<UserRedEnvelopeModel> implements ModelDriven<UserRedEnvelopeModel> {

    @Resource
    private UserRedEnvelopeService userRedEnvelopeService;

    @Resource
    @Qualifier("redEnvelopeCollectService")
    private CollectPayService collectService;

    private UserRedEnvelopeModel model = new UserRedEnvelopeModel();

    @Resource
    private UserIdentifyService userIdentifyService;

    @Resource
    private UserService userService;

    public UserRedEnvelopeModel getModel() {
        return model;
    }

    private Map<String, Object> data = new HashMap<String, Object>();

    /**
     * 获取用户可用红包列表
     *
     * @throws Exception
     */
    @Action(value = "/redEnvelope/useable", interceptorRefs = {@InterceptorRef("session"), @InterceptorRef("globalStack")})
    public void useable() throws Exception {
        User user = getSessionUser();
        checkInvestUser();
        List<UserRedEnvelopeModel> list = userRedEnvelopeService.useableList(user.getUserId());
        data.put("rows", list);
        printJson(getStringOfJpaObj(data));
    }

    /**
     * 初始化用户红包
     *
     * @throws Exception
     */
    @Action(value = "/redEnvelope/initUseable", interceptorRefs = {@InterceptorRef("session"), @InterceptorRef("globalStack")})
    public void initUseable() throws Exception {
        User user = getSessionUser();
        // 用户可用红包个数
        int count = userRedEnvelopeService.userableCount(user.getUserId());
        data.put("rdEnvelopeCount", count);

        // 红包最大占投资金额比例
        data.put("tenderRedpackageRate", SystemConfigHelper.getValue(Nid.USER_TENDER_REDPACKAGE_RATE));

        printJson(getStringOfJpaObj(data));
    }

    /**
     * 我的红包页面
     *
     * @return
     * @throws Exception
     */
    @Action(value = "/member/redpacket/availableRedEnvelope", results = {@Result(name = "availableRedEnvelope", type = "ftl", location = "/member/redpacket/availableRedEnvelope.html"),
            @Result(name = "availableRedEnvelope_firm", type = "ftl", location = "/member_borrow/redpacket/availableRedEnvelope.html")})
    public String availableRedEnvelope() throws Exception {
        //checkInvestUser();
        User user = getSessionUser();
        if (UserTypeUtils.isBorrowOrInverstment(user.getUserId())) {
            return "availableRedEnvelope_firm";
        }
        return "availableRedEnvelope";
    }

    /**
     * 我的红包数据
     *
     * @throws IOException
     */
    @Action("/member/redpacket/availableRedEnvelopeJSON")
    public void availableRedEnvelopeJSON() throws IOException {
        checkInvestUser();
        model.setUserId(getSessionUserId());
        PageDataList<UserRedEnvelopeModel> pageDataList = userRedEnvelopeService.list(model);
        int total = pageDataList.getPage().getTotal();// 总记录数
        data.put("total", total);
        data.put("data", pageDataList);
        printWebJson(getStringOfJpaObj(data));
    }

    /**
     * PS 现金红包兑换
     *
     * @throws Exception
     */
    @Action("/member/redpacket/redEnvelopeExchange")
    public void redEnvelopeExchange() throws Exception {
        User toUser = getSessionUser();

        UserIdentify ui = userIdentifyService.getUserIdentifyByUserId(toUser.getUserId());
        String tppUserCustId = UserUtils.getUserTppCustId(toUser.getUserId());
        if (ui.getRealNameStatus() != 1 || StringUtil.isBlank(tppUserCustId)) {
            throw new RedEnvelopeException("您还未开通第三方账户，请先开户！", 1);
        }

        cashRedEnvelopeExchange(model.getRedEnvelopeIds(), toUser.getUserId());
        printWebResult(MessageUtil.getMessage("MS100002003"), true);
    }

    /**
     * 红包兑现补单(代收)
     */
    @Action(NotifyUrl.RE_RED_ENVELOPE_COLLECT_REQ_URL)
    public void reEnvelopeExchangeCollect() {
        String token = paramString("token");
        if (!NotifyUrl.RE_CALL_TOKEN.equalsIgnoreCase(token)) {
            throw new RedEnvelopeException("补单令牌不正确,无法操作!", RedEnvelopeException.TYPE_JSON);
        }

        long userId = paramLong("user_id");
        if (userId == 0) {
            throw new RedEnvelopeException("用户ID不能为空!", RedEnvelopeException.TYPE_JSON);
        }

        User toUser = userService.getUserById(userId);
        if (toUser == null) {
            throw new RedEnvelopeException("该用户不存在!", RedEnvelopeException.TYPE_JSON);
        }

        int redType = paramInt("red_type");
        if (redType != RedEnvelopeType.CASH && redType != RedEnvelopeType.VIRTUAL) {
            throw new RedEnvelopeException("红包类型不正确!type=" + redType, RedEnvelopeException.TYPE_JSON);
        }

        String redIdStrings = paramString("red_ids");
        if (StringUtil.isEmpty(redIdStrings)) {
            throw new RedEnvelopeException("红包ID不能为空!", RedEnvelopeException.TYPE_JSON);
        }

        // 红包IDS
        List<String> redIdList = Splitter.on(",").omitEmptyStrings().splitToList(redIdStrings);
        int size = redIdList == null ? 0 : redIdList.size();
        long[] redIds = new long[size];
        if (size > 0) {
            for (int i = 0; i < size; i++) {
                redIds[i] = Long.valueOf(redIdList.get(i));
            }
            try {
                if (RedEnvelopeType.CASH == redType) {
                    cashRedEnvelopeExchange(redIds, toUser.getUserId());
                } else if (RedEnvelopeType.VIRTUAL == redType) {
                    virtualRedEnvelopeExchange(redIds, toUser.getUserId());
                } else {
                    // nothing
                }
            } catch (Exception e) {
                throw new RedEnvelopeException("补单失败!", RedEnvelopeException.TYPE_JSON);
            }
        } else {
            throw new RedEnvelopeException("没有可兑现红包!", RedEnvelopeException.TYPE_JSON);
        }
        try {
            printWebResult("补单成功", true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 红包兑现补单(代付)
     *//*
    @Action(NotifyUrl.RE_RED_ENVELOPE_PAY_REQ_URL)
    public void reEnvelopeExchangePay() {
        String token = paramString("token");
        if (!NotifyUrl.RE_CALL_TOKEN.equalsIgnoreCase(token)) {
            throw new RedEnvelopeException("补单令牌不正确,无法操作!", RedEnvelopeException.TYPE_JSON);
        }

        // 订单号
        String orderNo = paramString("order_no");
        if (StringUtil.isEmpty(orderNo)) {
            throw new RedEnvelopeException("代收的订单不存在!", RedEnvelopeException.TYPE_JSON);
        }

        // 根据订单号 查询代收Log
        TppTradeLog tppTradeLog = tppTradeLogDao.find(orderNo);

        // 生成新的订单
        tppTradeLog = redEnvelopeService.createPayOrder(tppTradeLog);
        // 发起代付
        redEnvelopeService.redEnvelopeExchangeForPay(tppTradeLog);
    }*/

    /**
     * 投标参与活动补单
     */
    @Action(NotifyUrl.RE_ACTIVITY_REQ_URL)
    public void reTenderActivity() {
        String token = paramString("token");
        if (NotifyUrl.RE_CALL_TOKEN.equalsIgnoreCase(token)) {
            throw new RedEnvelopeException("补单令牌不正确,无法操作!", RedEnvelopeException.TYPE_JSON);
        }

        long userId = paramLong("user_id");
        if (userId == 0) {
            throw new RedEnvelopeException("用户ID不能为空!", RedEnvelopeException.TYPE_JSON);
        }

        User toUser = userService.getUserById(userId);
        if (toUser == null) {
            throw new RedEnvelopeException("该用户不存在!", RedEnvelopeException.TYPE_JSON);
        }
    }

    /**
     * 现金红包兑现
     */
    private void cashRedEnvelopeExchange(long[] redEnvelopeIds, long exchangeUserId) {
        TppTradeLog tppTradeLog = collectService.createOrder(redEnvelopeIds, exchangeUserId, RedEnvelopeType.CASH, RedUseType.EXCHANGE_AMOUNT);
        ReturnResult returnResult = collectService.requestOrder(tppTradeLog);
        if (returnResult.isError()) {
            throw new RedEnvelopeException("红包兑现失败!", RedEnvelopeException.TYPE_JSON);
        }
    }

    /**
     * 虚拟红包兑现
     */
    private void virtualRedEnvelopeExchange(long[] redEnvelopeIds, long exchangeUserId) {
        TppTradeLog tppTradeLog = collectService.createOrder(redEnvelopeIds, exchangeUserId, RedEnvelopeType.VIRTUAL, RedUseType.EXCHANGE_AMOUNT);
        ReturnResult returnResult = collectService.requestOrder(tppTradeLog);
        if (returnResult.isError()) {
            throw new RedEnvelopeException("红包兑现失败!", RedEnvelopeException.TYPE_JSON);
        }
    }
}
